package com.lc.YYGH.user.service.Impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lc.YYGH.common.exception.YyghException;
import com.lc.YYGH.common.helper.JwtHelper;
import com.lc.YYGH.common.result.ResultStatus;
import com.lc.YYGH.enums.AuthStatusEnum;
import com.lc.YYGH.model.user.Patient;
import com.lc.YYGH.model.user.UserInfo;
import com.lc.YYGH.user.mapper.UserInfoMapper;
import com.lc.YYGH.user.service.PatientService;
import com.lc.YYGH.user.service.UserInfoService;
import com.lc.YYGH.vo.user.LoginVo;
import com.lc.YYGH.vo.user.UserAuthVo;
import com.lc.YYGH.vo.user.UserInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>implements UserInfoService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private PatientService patientService;
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        String phone=loginVo.getPhone();
        String code=loginVo.getCode();
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(code))
        {
            throw new YyghException(ResultStatus.FAIL);//如果手机号和验证码任何一个为空就抛出异常
        }
        //TODO 校验验证码 把code值和手机短信中的验证码进行比较
       String checkcode= redisTemplate.opsForValue().get(phone);

        if(!code.equals(checkcode)){

            throw new YyghException(ResultStatus.CODE_ERROR);
        }
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        UserInfo userInfo=baseMapper.selectOne(queryWrapper);
        if(null==userInfo)
        {
            //用户是第一次登录，就自动注册
            userInfo=new UserInfo();
            userInfo.setName("");
            userInfo.setPhone(phone);
            userInfo.setStatus(1);
            Date date=new Date();
            userInfo.setCreateTime(date);
            this.save(userInfo);
        }
        else
        {
            Date date=new Date();
            userInfo.setUpdateTime(date);
        }
        if(userInfo.getStatus()==0)
        {
            throw new YyghException(ResultStatus.LOGIN_DISABLED_ERROR);
        }

        Map<String,Object> map=new HashMap<>();
                String name=userInfo.getName();

        if(StringUtils.isEmpty(name))
        {
            name=userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name))
        {
            name=userInfo.getPhone();
        }
        map.put("name",name);
      String token =JwtHelper.createToken(userInfo.getId(),name);
        map.put("token",token);
        return map;


    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        UserInfo userInfo=baseMapper.selectById(userId);
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        baseMapper.updateById(userInfo);
    }

    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {

        String name = userInfoQueryVo.getKeyword(); //用户名称
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus(); //认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); //结束时间
        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("name",name);
        }
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper的方法
        IPage<UserInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pages.getRecords().stream().forEach(item -> {
            this.packageUserInfo(item);
        });
        return pages;
    }

    @Override
    public void lock(Long id, Integer status) {
        if(status.intValue()==0||status.intValue()==1)
        {
            UserInfo userInfo=this.getById(id);
            userInfo.setStatus(status);
            this.updateById(userInfo);
        }

    }
//详情
    @Override
    public Map<String, Object> show(Long userId) {
        Map<String,Object> map=new HashMap<>();
        UserInfo userInfo=this.packageUserInfo(baseMapper.selectById(userId));
        map.put("userInfo",userInfo);
        List<Patient> patientList=patientService.findAllByUserId(userId);
        map.put("patientList",patientList);
        return map;
    }

    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus.intValue()==2||authStatus.intValue()==-1)
        {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);

        }

    }

    private UserInfo packageUserInfo(UserInfo userInfo)
    {
        String statusNameByStatus=AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus());
        userInfo.getParam().put("authStatus",statusNameByStatus);
        String statusString=userInfo.getStatus().intValue()==0?"锁定":"正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }
}
